package vectorConstruction;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;

import myLucene.GetTime;
import myLucene.Props;
import myLucene.ReadQueries;
import myLucene.Searcher;
import myLucene.TfIdfOld;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.spans.SpanNearQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import prepro.SerializeTermsToInt;

public class IdiomVectorConstruction {

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Directory iDirectory = FSDirectory.open(new File(Props.readIndexPath));
		IndexSearcher searcher = new IndexSearcher(iDirectory, true);

		IndexReader iReader = searcher.getIndexReader();

		long start = System.currentTimeMillis();
		Props.writeToPath = "/local/joofeit/backIdioms_"+Props.windowSize;
		System.out.println(Props.writeToPath);
		System.out
				.println("Start VerbVectorConstruction: " + GetTime.getTime());
		String[] intToTerms = SerializeTermsToInt.deserializeArray();
		System.out.println("Construct SpanNearQueries");
		LinkedList<SpanNearQuery> idioms = ReadQueries.readIdioms();
		System.out.println("Construct SpanNearQueries.......Done");
		System.out.println("IdiomVectorConstruction idioms size: "
				+ idioms.size());
		for (SpanNearQuery sq : idioms) {
			long startQuery = System.currentTimeMillis();
			System.out.println(sq.toString());
			String queryAsString = queryToString(sq.toString(), intToTerms);
			System.out.println("#################################Start"
					+ queryAsString);
			queryToString(sq.toString(), intToTerms);
			System.out.println("Start ");
			boolean success2 = (new File(Props.writeToPath + "/TF").mkdir());
			boolean success3 = (new File(Props.writeToPath + "/Dist").mkdir());

			long startVerb = System.currentTimeMillis();

			Searcher.searchIdioms(iReader, sq, intToTerms);
			System.out.println("++++++++++++++++++++++++++++++++END "
					+ GetTime.getDuration(startQuery, System
							.currentTimeMillis()) + " " + queryAsString);
		}
		System.out.println("Time needed... "
				+ GetTime.getDuration(start, System.currentTimeMillis()));
		iReader.close();
	}

	public static String queryToString(String query, String[] intToTerms) {
		String[] qs = (query.split("]")[0].trim()).split("\\[")[1].split(",");
		String ints = "";
		String terms = "";
		for (String s : qs) {
			String ss = s.split(":")[1].trim();
			ints += ss + "_";
			terms += intToTerms[Integer.parseInt(ss)] + "_";
		}
		System.out.println("!!!!"
				+ (terms + "_" + ints)
						.substring(0, (ints + terms).length() - 1));

		return (terms + "_" + ints).substring(0, (terms + ints).length() - 1);
	}

}
